package com.hlz.rabbit.mq.qos;

import com.hlz.rabbit.mq.util.RabbitMqUtils;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author Hongliang Zhu
 * @create 2022-11-28 22:36
 */
public class QoSConsumer {

    public static void main(String[] args) throws IOException, TimeoutException {
        Channel channel = RabbitMqUtils.getChannel();
        channel.queueDeclare("qos_queue", false, false, false, null);

        // 每次消费一条数据
        channel.basicQos(1);

        // 自动ack关闭
        channel.basicConsume("qos_queue",false, new DefaultConsumer(channel) {

            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {

                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("receive a message: " + new String(body));

                // 手动ack
                channel.basicAck(envelope.getDeliveryTag(), false);
            }
        });

    }
}
